<!--
 * @Description: 
 * @Author: Gaq
 * @Date: 2022-11-19 19:34:11
 * @LastEditTime: 2022-11-28 21:33:21
 * @LastEditors: Gaq
-->
<script setup>
import { useStore } from "vuex";
import { useRoute, onBeforeRouteLeave } from "vue-router";
import request from "@/utils/request";
import router from "@/router";
import { ElMessage } from "element-plus";

const { state, commit, dispatch } = useStore();
const { proxy } = getCurrentInstance();
const route = useRoute();
const order = {
  userId: state.userId,
};
//从数据库中获取到的所有订单
let orderList = ref([]);
// 经过过滤的订单
const orderItem = ref([]);
const orderWait = ref([]);
let flag = ref(null);
const orderEvaluate = ref([]);
const dialogEvaluateVisible = ref(false);
const valueRate = ref();
const textarea = ref("");
const goodId = ref();
const goodEvaluate = {
  userId: state.userId,
  goodsId: "",
  styleId: "",
  detail: "",
  image: [],
  score: "",
};
// 控制订单信息对话框
const centerDialogVisible = ref(false);
let orderDetail = ref({});
let address = ref({});
let clickedOrder = {};
const disabled = ref(false);
const fileList = ref([]);
const files = ref(null);
const formData = new FormData();
const imgList = [];
let activeState = ref(1);
let waitTime = ref(""); //发货时间
let evaluateTime = ref(""); //评价时间
let confirmTime = ref(""); //确认收货时间

onBeforeMount(() => {
  request
    .post("/order/getPart", order)
    .then((res) => {
      orderList.value = res.data.orderList.filter(
        (item) => item.isDelete !== 1
      );
    })
    .then(() => {
      flag.value = route.params.flag;
    });
});
onBeforeRouteLeave((to, from) => {
  flag.value = to.params.flag;
});
watch(flag, (newVal, oldVal) => {
  filterOrder(newVal);
});
const filterOrder = (value) => {
  switch (value) {
    case "1":
      orderItem.value = orderList.value.filter(
        (item) => item.state == "已完成"
      );
      break;
    case "2":
      orderItem.value = orderList.value.filter(
        (item) => item.state == "已支付"
      );
      break;
    case "3":
      orderItem.value = orderList.value.filter(
        (item) => item.state == "已发货"
      );
      break;
    case "4":
      orderItem.value = orderList.value.filter(
        (item) => item.state == "待评价"
      );
      break;
  }
};

const handleRemove = (file) => {
  if (fileList.value.indexOf(file.raw) !== -1) {
    imgList.splice(fileList.value.indexOf(file.raw), 1);
    fileList.value.splice(fileList.value.indexOf(file.raw), 1);
  }
  files.value.handleRemove(file);
};

const onChange = (file) => {
  fileList.value.push(file.raw);
  formData.set("file", file.raw);
  request.post(`/uploadImg`, formData).then((res) => {
    imgList.push(res.data);
  });
};

const hideUpload = computed(() => {
  return fileList.value.length >= 3;
});
const showShopId = (value) => {
  clickedOrder = value;
  goodEvaluate.goodsId = value.goodsId;
  goodEvaluate.styleId = value.styleId;
};
// 提交评价
const submitData = () => {
  dialogEvaluateVisible.value = false;
  goodEvaluate.score = valueRate.value;
  goodEvaluate.detail = textarea.value;
  goodEvaluate.image = JSON.stringify(imgList);
  request.post("/goodsEvaluateMain/insertOne", goodEvaluate).then((res) => {
    res.code == 0
      ? (ElMessage.success("评价成功"),
        (evaluateTime.value = proxy.$formDate(Date())),
        (clickedOrder.state = "已完成"),
        request.put("/order/updateOne", clickedOrder),
        getOrder())
      : ElMessage.error(res.msg);
  });
};
const getOrder = () => {
  request.post("/order/getPart", order).then((res) => {
    orderList.value = res.data.orderList.filter((item) => item.isDelete !== 1);
    filterOrder(flag.value);
  });
};
// 确认收货
const confirmReceipt = (value) => {
  value.state = "待评价";
  request.put("/order/updateOne", value).then((res) => {
    res.code == 0
      ? (ElMessage.success("收货成功"), getOrder())
      : ElMessage.error(res.msg);
  });
};
// 判断点击的列的值，根据状态不同展示不同的进度数
const passData = (value) => {
  orderDetail.value = value;
  switch (orderDetail.value.state) {
    case "已支付":
      activeState.value = 1;
      break;
    case "已发货":
      activeState.value = 2;
      break;
    case "待评价":
      activeState.value = 3;
      break;
    case "已完成":
      activeState.value = 4;
      break;
  }
  // console.log(proxy.$formDate(orderDetail.value.createTime));
  request.get(`/address/getOne/${orderDetail.value.addressId}`).then((res) => {
    address.value = res.data;
  });
};
const deleteOrder = (value) => {
  request.delete(`/order/deleteOne/${value.orderId}`).then((res) => {
    res.code == 0
      ? (ElMessage.success("删除成功"), getOrder())
      : ElMessage.error(res.msg);
  });
};
</script>

<template>
  <el-scrollbar height="100vh">
    <div class="tableBox">
      <el-table :data="orderItem">
        <el-table-column width="100">
          <template #default="scope">
            <el-image :src="scope.row.image" style="height: 80px" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" show-overflow-tooltip>
          <template #default="scope">
            <span @click="(centerDialogVisible = true), passData(scope.row)">{{
              scope.row.name
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="styleName" label="款式">
          <template #default="scope">
            <span>{{ scope.row.styleName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="单价">
          <template #default="scope">
            <span style="color: red">￥{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="数量">
          <template #default="scope">
            <span>{{ scope.row.num }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template #default="scope">
            <div v-show="scope.row.state === '已支付'">
              <el-tag>{{ scope.row.state }}</el-tag>
            </div>
            <div v-show="scope.row.state === '已发货'">
              <el-tag class="ml-2" type="success">{{ scope.row.state }}</el-tag>
            </div>
            <div v-show="scope.row.state === '待评价'">
              <el-tag class="ml-2" type="info">{{ scope.row.state }}</el-tag>
            </div>
            <div v-show="scope.row.state === '已完成'">
              <el-tag class="ml-2" type="danger">{{ scope.row.state }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="">
          <template #default="scope">
            <div v-show="scope.row.state === '已支付'">
              <el-button type="warning" text>催发货</el-button>
            </div>
            <div v-show="scope.row.state === '已发货'">
              <el-button type="primary" text @click="confirmReceipt(scope.row)"
                >确认收货</el-button
              >
            </div>
            <div v-show="scope.row.state === '待评价'">
              <el-button
                type="info"
                text
                @click="(dialogEvaluateVisible = true), showShopId(scope.row)"
                >去评价</el-button
              >
            </div>
            <div v-show="scope.row.state === '已完成'">
              <el-button type="danger" @click="deleteOrder(scope.row)" text
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-scrollbar>
  <el-dialog v-model="dialogEvaluateVisible">
    整体评价：
    <el-rate
      v-model="valueRate"
      :texts="['失望', '不满', '一般', '满意', '惊喜']"
      :colors="['#99A9BF', '#F7BA2A', '#FF0000']"
      show-text
    />
    <div class="evaluateBox">
      <el-input
        v-model="textarea"
        autosize
        type="textarea"
        placeholder="Please input"
        clearable
      />
      <div style="margin-top: 10px">
        <el-upload
          ref="files"
          action="#"
          :class="{ hide: hideUpload }"
          list-type="picture-card"
          :auto-upload="false"
          :limit="3"
          :file-list="fileList"
          :on-change="onChange"
        >
          <i-ep-Plus />
          <template #file="{ file }">
            <div>
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url"
                alt=""
              />
              <span class="el-upload-list__item-actions">
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <i-ep-Delete />
                </span>
              </span>
            </div>
          </template>
        </el-upload>
        <p style="display: inline-block">{{ fileList.length }}/3</p>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogEvaluateVisible = false">取消</el-button>
        <el-button type="primary" @click="submitData"> 提交评价 </el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog v-model="centerDialogVisible">
    <div>
      <el-card class="box-card">
        <el-steps :active="activeState">
          <el-step
            title="拍下商品"
            :description="$formDate(orderDetail.createTime)"
          />
          <el-step title="卖家发货" :description="waitTime" />
          <el-step title="确认收货" :description="confirmTime" />
          <el-step title="评价" :description="evaluateTime" />
        </el-steps>
        <div class="addressInfoBox">
          <p>
            <i-ep-LocationInformation />
            {{ address.name }}
            <span style="color: rgb(177, 173, 173); font-size: small">{{
              address.phoneNumber
            }}</span>
          </p>
          <p style="font-size: small">
            {{ address.region }}{{ address.detail }}
          </p>
        </div>
        <div class="orderList">
          <img :src="orderDetail.image" alt="加载失败" />
          <div class="infoBox">
            <p :title="orderDetail.name">
              {{ orderDetail.name }}
            </p>
            <p class="price">
              ￥{{ (orderDetail.price * orderDetail.num).toFixed(2) }}
            </p>
            <p style="margin-top: 10px; font-size: smaller; color: #6c6c6c">
              样式名称：{{ orderDetail.styleName }}
            </p>
            <p style="position: absolute; right: 10px; bottom: 20px">
              ×{{ orderDetail.num }}
            </p>
          </div>
        </div>
      </el-card>
    </div>
  </el-dialog>
</template>

<style lang="less">
.tableBox .el-table tbody tr:hover > td {
  cursor: pointer;
  color: #972a2a;
  background-color: transparent !important;
}
.el-upload-list__item {
  transition: none !important;
}
.hide .el-upload--picture-card {
  display: none;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
.evaluateBox {
  margin-top: 10px;
}

.addressInfoBox {
  margin: 20px 0;
}
.orderList {
  margin-top: 10px;
  height: 120px;
  display: flex;
  position: relative;
  img {
    width: 120px;
    height: 120px;
  }
  .infoBox {
    margin-left: 10px;
    width: 410px;
    p {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}
.price {
  position: absolute;
  right: 0px;
  font-size: large;
  color: red;
}
</style>